package com.example.mycontentresolver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_id,et_name,et_age;
    private Button btn_insert,btn_delete,btn_update;
    private TextView textView;
    private ContentResolver resolver;
    private Uri uri;
    private ContentValues values;
    private int n=0;                //记录数据变化次数
    private String text;            //保存显示数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        showData();
    }

    private void init() {
        et_id=(EditText) findViewById(R.id.et_id);
        et_name=(EditText) findViewById(R.id.et_name);
        et_age=(EditText) findViewById(R.id.et_age);
        btn_insert =(Button) findViewById(R.id.btn_insert);
        btn_delete=(Button) findViewById(R.id.btn_delete);
        btn_update=(Button) findViewById(R.id.btn_update);
        textView=(TextView) findViewById(R.id.textView);
        btn_insert.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        btn_update.setOnClickListener(this);
        resolver=getContentResolver();
        uri=Uri.parse("content://com.example.mycontentprovider/info");
        values=new ContentValues();
        resolver.registerContentObserver(uri,true, new MyObserver(new Handler()));
    }

    private void showData() {
        List<Map<String,String>> data=new ArrayList<Map<String, String>>();
        if(n==0) {
             text = "程序运行后未执行增删改操作时的数据:\n";
        }else{
             text = "程序运行后经过第"+n+"次修改后的数据:\n";
        }
        Cursor cursor=resolver.query(uri,new String[]{"_id","name","age"},null, null,null);
        while(cursor.moveToNext()){
            Map<String,String> map=new HashMap<String, String>();
            map.put("_id",cursor.getString(0));
            map.put("name",cursor.getString(1));
            map.put("age",cursor.getString(2));
            data.add(map);
        }
        cursor.close();
        for(int i=0;i<data.size();i++){
            text+=data.get(i).get("_id")+"    "+data.get(i).get("name")+
                    "    "+data.get(i).get("age")+"\n";
        }
        textView.setText(text);
    }

    @Override
    public void onClick(View view) {
        String id=et_id.getText().toString();
        String name=et_name.getText().toString();
        String age=et_age.getText().toString();
        int count;      //保存修改或删除的记录数
        switch (view.getId()){
            case R.id.btn_insert:
                if(name.equals("")||age.equals("")){
                    Toast.makeText(this, "姓名和年龄不能为空，请输入姓名或年龄！", Toast.LENGTH_LONG).show();
                    return;
                }
                values.put("name",name);
                values.put("age",age);
                Uri newUri=resolver.insert(uri,values);
                Long n= ContentUris.parseId(newUri);      //使用ContentUris类的parseId()方法解析出Uri中的id值
                Toast.makeText(this, "新添加记录的编号（_id）是："+n.toString(), Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_delete:
                if(id.equals("")){
                    Toast.makeText(this, "请输入要删除记录的编号！", Toast.LENGTH_LONG).show();
                    return;
                }
                count=resolver.delete(uri,"_id=?",new String[]{id});
                Toast.makeText(this, "成功删除了"+count+"条记录！", Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_update:
                if(id.equals("")||name.equals("")||age.equals("")){
                    Toast.makeText(this, "编号、姓名、年龄都不能为空，请输入内容后重试！", Toast.LENGTH_LONG).show();
                    return;
                }
                values.put("name",name);
                values.put("age",age);
                count=resolver.update(uri,values,"_id=?",new String[]{id});
                Toast.makeText(this, "更新了"+count+"条记录！", Toast.LENGTH_LONG).show();
                break;
        }
    }
    private class MyObserver extends ContentObserver{
        public MyObserver(Handler handler) {
            super(handler);
        }
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            n++;               //监测数据的变化次数递增1
            showData();        //查询和显示记录数据
        }
    }
}
